package com.sskj.cndragon.turntable;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.MonthDisplayHelper;
import android.view.View;

import com.sskj.cndragon.R;

import java.util.ArrayList;
import java.util.List;

public class RotateView extends View {
    private Context mContext;
    //记录视图的大小
    private int mWidth;
    //背景圆形画笔
    private Paint bgPaint;
    //记录当前有几个分类
    private Paint mPaint;
    //背景圆环画笔
    private Paint circlePaint;
    //文字画笔
    private Paint textPaint;
    //扇面画笔
    private Paint arcPaint;
    //大图片
    private Bitmap mMain;

    //中心点横坐标
    private int mCenter;
    //绘制扇形的半径 减掉50是为了防止边界溢出  具体效果你自己注释掉-50自己测试
    private int mRadius;

    private RotateListener rotateListener;

    public RotateListener getRotateListener() {
        return rotateListener;
    }

    public void setRotateListener(RotateListener rotateListener) {
        this.rotateListener = rotateListener;
    }

    public RotateView(Context context) {
        super(context);
        init(context, null);
    }

    public RotateView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public RotateView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    //最低圈数 默认是3
    private int mMinTimes = 3;
    //分数数量
    private int mTypeNum = 6;
    //每个扇区旋转的时间
    private int mVarTime = 75;
    //文字合计
    private List<String> mDeses;
    //图片合集
    private List<Bitmap> mListBitmaps;
    //文字大小
    private float mTextSize;
    //文字颜色
    private int mTextColor;
    //第一次绘制扇形起始角度
    private int startAngle = -90;
    //每个扇形划过的角度
    private float sweepAngle;
    //转盘所在的正方形
    private RectF sectorRectf;

    private void init(Context context, AttributeSet attrs) {
        this.mContext = context;
        setBackgroundColor(Color.TRANSPARENT);
        bgPaint = new Paint();
        bgPaint.setStyle(Paint.Style.FILL);
        circlePaint = new Paint();
        circlePaint.setStyle(Paint.Style.STROKE);
        circlePaint.setColor(ContextCompat.getColor(mContext, R.color.colorAccent));
        circlePaint.setStrokeWidth(4);
        arcPaint = new Paint();
        arcPaint.setStyle(Paint.Style.FILL);
        sweepAngle = 360 / mTypeNum;
        startAngle -= sweepAngle / 2;
        textPaint = new Paint();
        textPaint.setLetterSpacing(0.2f);
        textPaint.setColor(Color.WHITE);
        textPaint.setStyle(Paint.Style.STROKE);
        textPaint.setTextSize(40);
        mListBitmaps = new ArrayList<>();
        mDeses = new ArrayList<>();
        for (int i = 0; i < mTypeNum; i++) {
            Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.app_logo);
            int ww = bitmap.getWidth();
            int hh = bitmap.getHeight();
            //定义矩阵对象
            Matrix matrix = new Matrix();
            //缩放原图
            matrix.postScale(1f, 1f);
            //向左旋转45度，参数为正则向右旋转
            matrix.postRotate(sweepAngle * i);
            Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, ww, hh, matrix, true);
            mListBitmaps.add(dstbmp);
            mDeses.add(String.valueOf(i + 1));
        }

        mMain = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.bg_zhuanpan);

        //其他画笔
        mPaint = new Paint();
        //设置填充样式
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        //设置边界模糊
        mPaint.setDither(true);
//        if (attrs != null) {
//            //获得这个控件对应的属性
//            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.wheelSurfView);
//
//        }


    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        Shader shader = new LinearGradient(50, 50, mWidth - 100, mWidth - 100, Color.parseColor("#E91E63"),
//                Color.parseColor("#2196F3"), Shader.TileMode.CLAMP);
//        bgPaint.setShader(shader);
//        canvas.drawCircle(mWidth / 2, mWidth / 2, mRadius - 20, bgPaint);
//        canvas.drawCircle(mWidth / 2, mWidth / 2, mRadius, circlePaint);
        //大圆盘
        Rect mDestRect = new Rect(0, 0, mWidth, mWidth);
        canvas.drawBitmap(mMain, null, mDestRect, mPaint);
        sectorRectf = new RectF(mCenter - mRadius, mCenter - mRadius, mCenter + mRadius, mCenter + mRadius);
        for (int i = 0; i < mTypeNum; i++) {
//            if (i % 2 == 0) {
//                arcPaint.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
//            } else if (i % 2 == 1) {
//                arcPaint.setColor(Color.TRANSPARENT);
//            }
//            canvas.drawArc(sectorRectf, startAngle, sweepAngle, true, arcPaint);

            drawText(startAngle, mDeses.get(i), mRadius, textPaint, canvas);

            int imgWidth = mRadius / 3;
            int w = (int) (Math.abs(Math.cos(Math.toRadians(Math.abs(180 - sweepAngle * i)))) * imgWidth +
                    Math.abs(Math.sin(Math.toRadians(Math.abs(180 - sweepAngle * i)))) * imgWidth);
            int h = (int) (Math.abs(Math.sin(Math.toRadians(Math.abs(180 - sweepAngle * i)))) * imgWidth +
                    Math.abs(Math.cos(Math.toRadians(Math.abs(180 - sweepAngle * i)))) * imgWidth);

            float angle = (float) Math.toRadians(startAngle + sweepAngle / 2);
            //确定图片在圆弧中心点位置
            float x = (float) (getWidth() / 2 + (mRadius / 2 + mRadius / 12) * Math.cos(angle));
            float y = (float) (getHeight() / 2 + (mRadius / 2 + mRadius / 12) * Math.sin(angle));
            //确定绘制图片的位置
            RectF rectF = new RectF(x - w / 2, y - h / 2, x + w / 2, y + h / 2);
//            canvas.drawRect(rectF, textPaint);
//            canvas.drawBitmap(mListBitmaps.get(i), null, rectF, null);
            drawIcons(canvas, mListBitmaps.get(i), startAngle);

            startAngle += sweepAngle;
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int desiredWidth = 800;

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        int width;

        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            width = Math.min(desiredWidth, widthSize);
        } else {
            width = desiredWidth;
        }

        //将测得的宽度保存起来
        this.mWidth = width;
        mCenter = mWidth / 2;
        //绘制扇形的半径 减掉50是为了防止边界溢出
        mRadius = mWidth / 2 - 50;

        setMeasuredDimension(width, width);
    }


    //绘制文字
    private void drawText(float startAngle, String string, int radius, Paint textPaint, Canvas canvas) {
        //创建绘制路径
        Path circlePath = new Path();
        //范围也是整个圆盘
        RectF rect = new RectF(mCenter - radius, mCenter - radius, mCenter
                + radius, mCenter + radius);
        //给定扇形的范围
        circlePath.addArc(sectorRectf, startAngle, sweepAngle);

        //圆弧的水平偏移
        float textWidth = textPaint.measureText(string);
        //圆弧的垂直偏移
        float hOffset = (float) (Math.sin(sweepAngle / 2 / 180 * Math.PI) * radius) - textWidth / 2;

        //绘制文字
        canvas.drawTextOnPath(string, circlePath, hOffset, radius / 4, textPaint);
    }

    private void drawIcons(Canvas canvas, Bitmap mBitmap, int startAngle) {
        int imageWidth = mRadius / 10;
        //计算半边扇形的角度 度=Math.PI/180 弧度=180/Math.PI
        float angle = (float) ((startAngle + sweepAngle / 2) * Math.PI / 180);
        //计算中心点的坐标
        int r = mRadius / 2;
        float x = (float) (mCenter + r * Math.cos(angle));
        float y = (float) (mCenter + r * Math.sin(angle));
        //设置绘制图片的范围
        RectF rectF = new RectF(x - imageWidth, y - imageWidth, x + imageWidth, y + imageWidth);
        canvas.drawRect(rectF,mPaint);
        canvas.drawBitmap(mBitmap, null, rectF, null);
    }

    //目前的角度
    private float currAngle = 0;
    //记录上次的位置
    private int lastPosition;

    public void startRotate(final int pos) {
        //最低圈数是mMinTimes圈
        int newAngle = (int) (360 * mMinTimes + (pos - 1) * sweepAngle + currAngle - (lastPosition == 0 ? 0 : ((lastPosition - 1) * sweepAngle)));
        //计算目前的角度划过的扇形份数
        int num = (int) ((newAngle - currAngle) / sweepAngle);
        final ObjectAnimator anim = ObjectAnimator.ofFloat(RotateView.this, "rotation", currAngle, newAngle);
        currAngle = newAngle;
        lastPosition = pos;
        //动画持续时间
        anim.setDuration(num * mVarTime);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (rotateListener != null) {
                    rotateListener.rotating(animation);
                }
            }
        });
        final float[] f = {0};
        anim.setInterpolator(new TimeInterpolator() {
            @Override
            public float getInterpolation(float input) {
                float f1 = (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
                Log.e("HHHHHHHh", "" + input + "     " + (f[0] - f1));
                f[0] = (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
                return f[0];
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (rotateListener != null) {
                    //去空格和前后空格后输出
                    String des = mDeses.get((mTypeNum - pos + 1) %
                            mTypeNum).trim().replaceAll(" ", "");
                    rotateListener.rotateEnd(pos, des);
                }
            }
        });
        anim.start();
    }
}
